package com.example.usergroup.viewmodel;

import androidx.databinding.ObservableField;

import com.alibaba.android.arouter.launcher.ARouter;
import com.example.mvvmcommon.mvvm.viewmodel.BaseViewModel;
import com.example.networkmoudel.entity.BaseEntity;
import com.example.usergroup.data.entity.UserDaoEntity;
import com.example.usergroup.data.entity.UserEntity;
import com.example.usergroup.data.entity.UserEventEntity;
import com.example.usergroup.model.LoginModel;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.Map;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class LoginViewModel extends BaseViewModel<LoginModel> {

    public ObservableField<String>pwd=new ObservableField<>();
    public ObservableField<String>mobile=new ObservableField<>();
    @Override
    protected void initData() {
        EventBus.getDefault().register(this);

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void update(UserEventEntity entity){
        if (entity.action.equals("update")) {
            mobile.set(entity.phone);
            pwd.set(entity.pwd);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected LoginModel createModel() {
        return new LoginModel();
    }

    @Override
    protected void sucessFull(BaseEntity entity) {
        if (entity instanceof UserEntity){
            UserEntity userEntity = (UserEntity) entity;
            new UserDaoEntity().update(userEntity.data);
            UserEventEntity userEventEntity = new UserEventEntity();
            userEventEntity.action = "updateUser";
            EventBus.getDefault().post(userEventEntity);
            toBack();
        }
    }
    public void Logbnt(){
        Map<String,Object> map=new HashMap<>();
        map.put("mobile", mobile.get());
        map.put("pushId", "123456");
        map.put("pwd", pwd.get());
        m.requestLogin(map).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(this);
    }

    public void toReg(){
        ARouter.getInstance().build("/user/toReg").navigation();
    }

    public void toBack(){
        getUiChangeLiveData().getFinishActivity().setValue("asd");
    }
    public void toForgetPwd(){
        ARouter.getInstance().build("/user/forgetpwd").navigation();
    }
}
